/*
 * Copyright (c) 2020 - present, Inspur Genersoft Co., Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *        http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.inspur.edp.web.npmpackage.core.npmsetting;

import com.inspur.edp.web.common.io.NodejsFunctionUtility;
import com.inspur.edp.web.common.serialize.SerializeUtility;
import com.inspur.edp.web.npmpackage.api.constant.I18nMsgConstant;
import com.inspur.edp.web.npmpackage.api.entity.NpmPackageResponse;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmRepository;
import com.inspur.edp.web.npmpackage.api.entity.settings.NpmSettings;

import java.util.UUID;

/**
 * npm 配置管理
 *
 * @author noah
 */
public class NpmSettingManager {


    /**
     * 获取对应的npm配置文件内容
     *
     * @param isUpgradeTool
     * @return
     */
    public static NpmSettings getNpmSetting(boolean isUpgradeTool) {
        // 获取nodejs路径
        String nodeJsPath = NodejsFunctionUtility.getNodeJsPathInServer();
        // 从配置文件中读取对应的内容
        NpmSettings npmSettings = NpmSettingReader.read(nodeJsPath);
        if (npmSettings == null) {
            // 如果未成功读取到文件内容 那么取默认值
            npmSettings = NpmSettingInitialization.initialize();
            String serializedNpmSetting = SerializeUtility.getInstance().serialize(npmSettings, true);
            // 参数保存至配置文件
            NpmSettingWriter.write(nodeJsPath, serializedNpmSetting);
        }

        return npmSettings;
    }

    /**
     * npm配置信息保存
     *
     * @param npmSettings npm配置信息
     * @return
     */
    public static NpmPackageResponse saveNpmSetting(NpmSettings npmSettings) {

        if (npmSettings == null) {
            return NpmPackageResponse.createError(I18nMsgConstant.WEB_NPM_PACKAGE_MSG_0019);
        }

        NpmSettings oldNpmSettings = NpmSettingManager.getNpmSetting(false);

        // 针对保存  如果对应的id不存在 那么设置为随机数 并返回至前端
        for (NpmRepository npmRepository : npmSettings.getSettingConfig().getRepositories()) {
            if (npmRepository.getId() == null || npmRepository.getId().length() == 0) {
                UUID uuid = UUID.randomUUID();
                npmRepository.setId(uuid.toString());
                npmRepository.setPasswordChanged(null);
                continue;
            }
            // 默认仓库只允许修改更新策略
            if ("prod".equals(npmRepository.getId())) {
                NpmRepository prodRepository = NpmSettingInitialization.initialize().getSettingConfig().getRepositories()[0];
                npmRepository.setPassword(prodRepository.getPassword());
                npmRepository.setUserName(prodRepository.getUserName());
                npmRepository.setNeedLogin(prodRepository.isNeedLogin());
                npmRepository.setCanDelete(prodRepository.isCanDelete());
                npmRepository.setLastUpdated(prodRepository.getLastUpdated());
                npmRepository.setUrl(prodRepository.getUrl());
                npmRepository.setName(prodRepository.getName());
                npmRepository.setId(prodRepository.getId());
                npmRepository.setPasswordChanged(null);
                continue;
            }

            for (NpmRepository oldNpmRepository : oldNpmSettings.getSettingConfig().getRepositories()) {
                if (npmRepository.getId().equals(oldNpmRepository.getId())) {
                    // 如果密码未修改 则使用旧密码
                    if (npmRepository.getPasswordChanged() == null || !npmRepository.getPasswordChanged()) {
                        npmRepository.setPassword(oldNpmRepository.getPassword());
                    }
                    npmRepository.setPasswordChanged(null);
                }
            }
        }

        String nodeJsPath = NodejsFunctionUtility.getNodeJsPathInServer();
        String serializedNpmSetting = SerializeUtility.getInstance().serialize(npmSettings, true);
        // 参数保存至配置文件
        NpmSettingWriter.write(nodeJsPath, serializedNpmSetting);
        return NpmPackageResponse.create();
    }


}
